﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using PsTFS.Methodes;
using PsTFS.Objects;

namespace PsTFS.Commandes.Get
{
	/// <summary>
	/// Récupération de la liste des build pour un projet d'un serveur TFS
	/// </summary>
	[Cmdlet(VerbsCommon.Get, "Build")]
	public class GetBuild : PsCmdlet
	{
		/// <summary>
		/// Constructor
		/// </summary>
		public GetBuild()
		{
			QueryOrder = BuildQueryOrder.FinishTimeDescending;
		}

		/// <summary>
		/// Lancement du processus de récupération des BUILD d'un projet
		/// </summary>
		protected override void ProcessRecord()
		{
			try
			{
				var buildDetailSpec = string.IsNullOrEmpty(BuildDefinition)
					? Context.Instance.BuildServer.CreateBuildDetailSpec(ProjectName)
					: Context.Instance.BuildServer
						.CreateBuildDetailSpec(ProjectName,
							BuildDefinition);
				if (First > 0)
				{
					buildDetailSpec.MaxBuildsPerDefinition = First;
				}
				if (!string.IsNullOrEmpty(BuildNumber))
				{
					buildDetailSpec.BuildNumber = BuildNumber;
				}
				buildDetailSpec.QueryOrder = QueryOrder;
				// Renvois de la liste des projets
				WriteObject((Context.Instance.BuildServer.QueryBuilds(buildDetailSpec).Builds).ToList());
			}
			catch (Exception ex)
			{
				var err = ErrorRecord(ex, ErrorCategory.WriteError);
				WriteError(err);
				Log.AddLog(ex.StackTrace);
			}
			finally
			{
				base.ProcessRecord();
			}
		}

		/// <summary>
		/// Permet d'informer la fin de la commande
		/// </summary>
		protected override void EndProcessing()
		{
			Log.AddLog(null, "Get-Build finished");
			base.EndProcessing();
		}

		/// <summary>
		/// Object contenant Team Foundation Server
		/// </summary>
		[Parameter(Position = 0)]
		public TfsTeamProjectCollection TFS
		{
			set { Context.Instance.TFS = value; }
		}

		/// <summary>
		/// Nom du label
		/// </summary>
		[Parameter(Position = 1, Mandatory = true)]
		public string ProjectName { get; set; }

		[Parameter(HelpMessage = "Build definition name", Position = 2, Mandatory = true)]
		public string BuildDefinition { get; set; }

		[Parameter(HelpMessage = "Sort order of the query", Position = 3)]
		[ValidateNotNullOrEmpty]
		public BuildQueryOrder QueryOrder { get; set; }

		[Parameter(HelpMessage = "Build number to return", Position = 4)]
		[ValidateNotNullOrEmpty]
		public string BuildNumber { get; set; }

		[Parameter(HelpMessage = "Number of records to receive", Position = 5)]
		[ValidateNotNullOrEmpty]
		public int First { get; set; }
	}
}